module SessionsHelper
	
	def current_user=(user)
		@current_user = user
	end
	
	def current_user
		@current_user ||= (User.find_by_remember_token(cookies[:remember_token]) || GuestUser.new)
	end

	def current_user?(user)
		user == current_user
	end
		
	def logged_in?
		!current_user.guest?
	end
	
	def log_in user, remember_me=false
		self.current_user = user
		user.update_attribute(:last_login, DateTime.now)
		
		# For flash message to be in the correct language
		I18n.locale = user.preferred_locale unless user.preferred_locale.blank?
		
		if remember_me 
			cookies.permanent[:remember_token] = user.remember_token
		else
			cookies[:remember_token] = user.remember_token
		end
	end
	
	def log_out
		self.current_user = GuestUser.new
		cookies.delete(:remember_token)
		redirect_back_or home_path, notice: t('session.destroy.successful')
	end  
		
	def require_logged_in
		unless logged_in?
			redirect_to login_path, notice: t('user.log_in_required')
		end
	end
	
	def redirect_back_or(default, flash={})
		redirect_to(session[:return_to] || default, flash)
		session.delete(:return_to)
	end

	def store_location
		session[:return_to] = request.fullpath
	end
	
end
